<template>
  <div class="h-full page-normal">
    <a-table
      id="sortTable"
      ref="tableRef"
      :columns="columns"
      :data-source="copyList"
      :pagination="false"
      :loading="loading"
      :scroll="{ x: 1500 }"
      class="max-h-[75vh] overflow-y-scroll"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-if="column.key === 'site_icon'">
          <a-image
            width="37.6px"
            height="39.85px"
            class="w-[-webkit-fill-available] object-contain"
            :src="getIcon(record)"
            :fallback="defaultImage"
          />
        </template>
        <template v-else-if="column.key === 'site_name'">
          <Tooltip :str="record.site_name" v-if="record.site_name" width="120px" />
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'site_type'">
          <span>
            {{ record.site_type === 1 ? '种源资源' : '外部资源' }}
          </span>
        </template>
        <template v-else-if="column.key === 'site_video_count'">
          <span>
            {{ formatNumber(+record.site_video_count) }}
          </span>
        </template>
        <template v-else-if="column.key === 'site_picture_count'">
          <span>
            {{ formatNumber(+record.site_picture_count) }}
          </span>
        </template>
        <template v-else-if="column.key === 'site_article_count'">
          <span>
            {{ formatNumber(+record.site_article_count) }}
          </span>
        </template>
        <template v-else-if="column.key === 'site_task_count'">
          <span>
            {{ formatNumber(+record.site_task_count) }}
          </span>
        </template>
        <template v-else-if="column.key === 'created_at'">
          <span>
            {{ formatToDateTime(+record.created_at * 1000) }}
          </span>
        </template>
        <template v-else-if="column.key === 'site_status'">
          <span>
            <a-switch
              v-model:checked="record.site_status"
              :checkedValue="1"
              :unCheckedValue="2"
              @click="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a style="color: #0083ff" @click="handleManage(record)">管理内容</a>
            <a-divider type="vertical" />
            <a style="color: #0083ff" @click="updateSite(record.site_id)">编辑</a>
            <a-divider type="vertical" />
            <a @click="deleteSite(record.site_id)" :class="type === 2 ? 'common-blue' : 'common-del'"> 删除 </a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 禁用对话框 -->
    <modal-view
      title="提示"
      v-model:visible="disabledVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="disableConfirm"
      @cancel="disableCancel"
    >
      <span>{{ type === 1 ? disabledText : activeText }}</span>
    </modal-view>

    <!-- 删除对话框 -->
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>删除站点不可恢复，可能导致使用该站点的应用内容为空，确定要删除吗？</span>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { formatNumber, formatToDateTime } from '@/utils/format'
import { computed, inject, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import type { SiteItem } from '@/types/site/site'
import ModalView from '@/components/components/modal/ModalView.vue'
import Tooltip from '@/components/components/Tooltip.vue'
import Sortable from 'sortablejs'
import { column } from '../dataSource'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import useStore from '@/stores'
import { storage } from '@/utils/storage'
import apis from '@/apis'
import defaultImage from '@/assets/icon/defaultImage.png'
const tableRef = ref()
const {
  site: { edit_status, del, update }
} = apis
const emit = defineEmits(['updateList'])
const baseUrl: any = inject('baseUrl')
const { permission } = useStore()
const router = useRouter()
const props = defineProps<{ type: number; list: any }>()
let copyList = props.list
const loading = ref(false)
const deleteId = ref()
const deleteVisible = ref(false)
const disabledVisible = ref(false)
const isChecked = ref(1) //是否禁用
const disabledId = ref() //禁用id
const columns = ref(column)
const activeText = ref('确定要启用该站点吗？')
const disabledText = ref('禁用站点可能导致使用该站点的应用内容为空，确定要禁用该站点吗？')
const updateSite = (id: string) => {
  router.push({ name: 'EditSite', query: { id: id } })
}

watch(
  () => props.list,
  (val) => {
    console.log({ val }, 123333333333)
  },
  {
    immediate: true,
    deep: true
  }
)

/**
 * @description 删除
 * @param {id}
 */
const deleteSite = (id: string) => {
  deleteId.value = id
  if (props.type === 1) {
    return message.warning('启用中站点不能删除！')
  } else {
    deleteVisible.value = true
  }
}
/** 修改站点禁用状态 */
const editStatus = (checked: number, row: SiteItem) => {
  // const data = {
  //   type: 1,
  //   status: checked,
  //   id: [row.site_id]
  // }
  // edit_status(data).then(() => {
  //   message.success(checked === 1 ? '启用成功' : '禁用成功')
  //   emit('updateList')
  // })
  if (props.type === 1) {
    disabledVisible.value = true
    isChecked.value = checked
    disabledId.value = row.site_id
  } else {
    const data = {
      type: 1,
      status: checked,
      id: [row.site_id]
    }
    edit_status(data).then(() => {
      message.success('启用成功')
      emit('updateList')
    })
  }
}
//禁用站点
const disableConfirm = (value: any) => {
  console.log('value: ', value)
  const data = {
    type: 1,
    status: isChecked.value,
    id: [disabledId.value]
  }
  edit_status(data).then(() => {
    message.success('禁用成功')
    disabledVisible.value = value
    emit('updateList')
  })
}
const disableCancel = () => {
  disabledVisible.value = false
  emit('updateList')
}
//内容管理
const handleManage = (item: SiteItem) => {
  nextTick(() => {
    console.log('item: ', item.site_name, item.site_order)
    permission.setSiteName(item.site_name)
    permission.setSiderType('SITE')
    router.push({ name: 'FilmManage' })
    storage.set('siteId', item.site_id)
    storage.set('siteType', item.site_type)
  })
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  del({ site_id: deleteId.value }).then(() => {
    message.success('删除成功')
    deleteVisible.value = value
    emit('updateList')
  })
}
//根据类型获取图片
const getIcon = computed(() => (item: SiteItem) => {
  if (item.site_icon_type === 1) return baseUrl + item.site_icon
  return item.site_icon
})
//删除站点
const deleteCancel = () => {
  deleteVisible.value = false
}
//调用排序接口
const sortFunc = (item: any) => {
  loading.value = true
  update({
    ...item
  }).then(() => {
    message.success('排序成功')
    emit('updateList')
    loading.value = false
  })
}
const sotrableObj = ref()
//初始化表格拖动
const initSortable = () => {
  console.log('tableRef.value: ', tableRef.value)
  const el = tableRef.value.table.$el.querySelector('#sortTable tbody') as HTMLElement
  console.log({ el })
  if (!el) return false
  sotrableObj.value = new Sortable(el, {
    handle: '.ant-table-row',
    animation: 150,
    ghostClass: 'blue-background-class',
    forceFallback: true,
    sort: true,
    // async
    onEnd(item) {
      // console.log({ item }, '被拖动了')
      if (item.newIndex === item.oldIndex) return
      const startIndex = (item.oldIndex as number) - 1
      const endIndex = (item.newIndex as number) - 1
      const { site_name, site_id, site_icon, site_icon_type, site_introduction, site_status } = copyList[startIndex]
      const { site_order } = copyList[endIndex]
      sortFunc({ site_name, site_id, site_icon, site_order, site_icon_type, site_introduction, site_status })
    }
  })
}

onMounted(() => {
  initSortable()
})
onUnmounted(() => {
  // sotrableObj.value.destroy()
})
defineExpose({ initSortable })
</script>
<style lang="less" scoped>
.page-normal {
  :deep(.ant-table-cell):hover {
    cursor: pointer;
  }
  .common-blue {
    color: #0083ff;
  }

  .common-del {
    color: #bfbfbf;
  }
  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }
  // :deep(.ellipsis-text) {
  //   max-width: 154px !important;
  //   white-space: nowrap;
  //   overflow: hidden;
  //   white-space: nowrap;
  //   text-overflow: ellipsis;
  //   cursor: pointer;
  // }
}
</style>
